# pyinstaller -D -p C:\\ProgramData\\Miniconda3\\envs\\autopick\\Lib\\site-packages labels.py
import autocheck
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import cv2
import sys
import os
class labels:  
    def __init__(self, csvfile,output_labels_file=r'labels.txt'):
        self.csvfile = csvfile
        self.labels = {1:'tumour',2:'artifact'}
        self.output_labels_file = output_labels_file
        self.autocheck = autocheck.ImageProcessor(csvfile,0.5)
        ## labeles##
        self.average = None
        self.are_count = None
        self.are_sum = None
        self.aspect_ratio = None
        self.area_center = None
    
    def get_points(self,image):
        self.autocheck.image_enhancement()
        self.autocheck.Set_fence_value()
        points = self.autocheck.save_polygon()
        
      
    def show_image(self,image):
        points = self.autocheck.polygon_points
        if points != []:
            # 绘制要提取数据的图像
            data = pd.read_csv(image)
            #plt.imshow(data, cmap='jet',vmin=0, vmax=100)    
            # 绘制边界框
            for i,region in enumerate(points):
                plt.plot(region[0], region[1], 'r-', linewidth=1)
                centroid_x = np.mean(region[0])
                centroid_y = np.mean(region[1])
                plt.text(centroid_x, centroid_y, str(i+1), color='r', fontsize=10, ha='center', va='center')
            # 显示图形
            #plt.show(block=False) 
            plt.imshow(data, cmap='jet', vmin=0, vmax=100)
            #plt.ion() 
            plt.show(block=False) 
        else:
            print("未找到可疑点")  
            data = pd.read_csv(image)
            plt.imshow(data, cmap='jet', vmin=0, vmax=100)
            plt.show() 
        
                        
    def Tag_image_main(self,image): #程序的主函数入口
        # self.autocheck.image_enhancement()
        # points = self.autocheck.save_polygon()
        points = self.autocheck.polygon_points
        if points != []:
            for i,region in enumerate(points):
                print("请输入区域%d标记分类,接受数字 1:肿瘤 2:结节 3:乳头 4其他分类..." % (i+1))
                num1 = int(input("请输入一个整数 :"))
                self.save_labels(region,num1)  
        else :
            print("未找到可疑点")      
    
    def labels_strategy(self,region):#未来加入策略筛选读取配置文件
        self.labels_average_layer()
        self.labels_area(region)
        self.labels_sum(region)
        self.labels_WHratio(region)
        self.labels_area_center(region)
    
    def labels_average_layer(self):
        self.average = np.mean(self.autocheck.image)

    
    def labels_area(self,region):
        data = self.autocheck.image
        row,col = data.shape
        mask = np.zeros((row, col))
        temp_points = np.column_stack((region[0], region[1]))
        #print(temp_points)
        cv2.fillPoly(mask, [temp_points], 1)
        data_with_polygon = np.multiply(data, mask)
        count = np.sum(data_with_polygon != 0)
        self.are_count = count
    
    def labels_area_center(self,region):
        temp_points = np.column_stack((region[0], region[1]))
        area_center = np.mean(temp_points, axis=0)
        rounded_area_center = np.round(area_center, decimals=1)
        self.area_center = rounded_area_center
        
    def labels_sum(self,region):
        data = self.autocheck.image
        row,col = data.shape
        mask = np.zeros((row, col))
        temp_points = np.column_stack((region[0], region[1]))
        cv2.fillPoly(mask, [temp_points], 1)
        masked_data  = np.ma.masked_array(data, mask=1-mask)
        # plt.imshow(mask, cmap='gray')
        # plt.colorbar()
        # plt.show()
        sum_data = np.sum(masked_data)
        self.are_sum = sum_data
    
    def labels_WHratio(self,region):
        temp_points = np.array(list(zip(region[0], region[1])))
        xmin, xmax = np.min(temp_points[:, 0]), np.max(temp_points[:, 0])
        ymin, ymax = np.min(temp_points[:, 1]), np.max(temp_points[:, 1])
        width = xmax - xmin
        height = ymax - ymin
        self.aspect_ratio = width / height
        
    
    def save_labels(self,region,species,label_filename=None):
        autocheck_object = self.autocheck
        if label_filename is None:
            label_filename = self.output_labels_file
        self.labels_strategy(region)
        current_path = os.path.dirname(os.path.abspath(__file__))
        absolute_path = os.path.join(current_path, label_filename)
        print(absolute_path)
        file = open(absolute_path, "a")
        # 文件名 宽 高 单层血红蛋白浓度均值 可疑区域像素个数 可疑区域血红蛋白总值 可疑区域宽高比  区域中心位置 所属种类
        file.write(str(self.csvfile)+','+str(autocheck_object.width)+','+str(autocheck_object.height)+','+\
		           str(self.average)+','+str(self.are_count)+','+str(self.are_sum)+','+str(self.aspect_ratio)+','+\
                   str(self.area_center)+','+str(species)+'\n')
        file.close()
        
        
        
if __name__=='__main__':
    # if len(sys.argv) < 2:
    #     print("请提供输入文件路径")
    #     sys.exit()
    # ## 获取输入文件路径
    # input_file = sys.argv[1]
    input_file = r'data/202312040003_RCW_aD_2.csv'
    save_label = labels(input_file)
    save_label.get_points(input_file)
    save_label.show_image(input_file)
    save_label.Tag_image_main(input_file)